#include "DataStore.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <windows.h>

// GBK 转 UTF-8（仅 Windows）
std::string to_utf8(const std::string& gbk_str) {
    // GBK -> WideChar (UTF-16)
    int len = MultiByteToWideChar(CP_ACP, 0, gbk_str.c_str(), -1, nullptr, 0);
    std::wstring wstr(len, 0);
    MultiByteToWideChar(CP_ACP, 0, gbk_str.c_str(), -1, &wstr[0], len);

    // WideChar -> UTF-8
    int utf8_len = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
    std::string utf8_str(utf8_len, 0);
    WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &utf8_str[0], utf8_len, nullptr, nullptr);

    return utf8_str;
}

FileDataStore::FileDataStore(const std::string& filename) : filename(filename) {}

void FileDataStore::save(const std::vector<Task>& tasks) {
    std::ofstream outFile(filename, std::ios::out | std::ios::binary); // 以二进制模式写入
    if (!outFile.is_open()) {
        throw std::runtime_error("无法打开文件进行保存: " + filename);
    }
    
    // 写入 UTF-8 BOM
    outFile << "\xEF\xBB\xBF";
    
    for (const auto& task : tasks) {
        std::string desc = task.getDescription();
        // 简单引号包裹（假设描述不含引号）
        std::string quoted_desc = "\"" + desc + "\"";
        
        outFile << task.getId() << ","
                << quoted_desc << ","
                << static_cast<int>(task.getPriority()) << ","
                << task.getDueDate() << "\n";
    }
}

std::vector<Task> FileDataStore::load() {
    std::vector<Task> loadedTasks;
    std::ifstream inFile(filename, std::ios::in | std::ios::binary); // 以二进制模式读取
    if (!inFile.is_open()) {
        return loadedTasks;
    }
    
    // 跳过 UTF-8 BOM
    char bom[3];
    inFile.read(bom, 3);
    if (!(bom[0] == '\xEF' && bom[1] == '\xBB' && bom[2] == '\xBF')) {
        inFile.seekg(0);
    }
    
    std::string line;
    while (std::getline(inFile, line)) {
        std::vector<std::string> tokens;
        std::string token;
        bool in_quotes = false;
        std::stringstream iss(line);
        
        // 手动解析逗号分隔字段
        while (iss.peek() != EOF) {
            char c = iss.get();
            if (c == '"') {
                in_quotes = !in_quotes;
            } else if (c == ',' && !in_quotes) {
                tokens.push_back(token);
                token.clear();
            } else {
                token += c;
            }
        }
        if (!token.empty()) {
            tokens.push_back(token);
        }
        
        // 调试：打印解析的字段
        std::cout << "Parsed line: ";
        for (const auto& t : tokens) {
            std::cout << "[" << t << "] ";
        }
        std::cout << std::endl;
        
        if (tokens.size() == 4) {
            try {
                int id = std::stoi(tokens[0]);
                std::string description = tokens[1];
                
                // 移除引号
                if (!description.empty() && description.front() == '"' && description.back() == '"') {
                    description = description.substr(1, description.size() - 2);
                }
                
                Priority priority = static_cast<Priority>(std::stoi(tokens[2]));
                std::string dueDate = tokens[3];
                
                loadedTasks.emplace_back(id, description, priority, dueDate);
            } catch (...) {
                std::cout << "Skipping invalid line: " << line << std::endl;
                continue;
            }
        } else {
            std::cout << "Invalid field count: " << tokens.size() << ", Line: " << line << std::endl;
        }
    }
    
    return loadedTasks;
}